<?php

namespace yunj\core\validate;

use yunj\core\constants\BuilderConst;
use yunj\core\Validate;

class YunjFormValidate extends Validate {

    protected $rule = [
        BuilderConst::ID_KEY => 'require',
        BuilderConst::ASYNC_TYPE_KEY => 'require|in:submit',
    ];

    protected $message = [
        BuilderConst::ID_KEY.'.require' => '访问错误',
        BuilderConst::ASYNC_TYPE_KEY.'.require' => '['.BuilderConst::ASYNC_TYPE_KEY.']参数缺失',
        BuilderConst::ASYNC_TYPE_KEY.'.in' => '['.BuilderConst::ASYNC_TYPE_KEY.']参数错误',
    ];

    protected $scene = [
        'AsyncRequest' => [BuilderConst::ID_KEY, BuilderConst::ASYNC_TYPE_KEY],
    ];

    protected function handleData(array &$data, $scene): void {
        if ($scene == 'AsyncRequest') {
            switch ($data[BuilderConst::ASYNC_TYPE_KEY]) {
                case 'submit':
                    $data = $this->handleDataBySubmit($data);
                    break;
            }
        }
    }

    private function handleDataBySubmit(array &$data) {
        if (!isset($data['data'])) throw_error_json('[data]参数缺失');
        $data['data'] = json_decode($data['data'], true);
        return $data;
    }
}